<script setup>
	import {
		computed,
		ref,
		watch
	} from "vue";
	// 商品列表数据
	const goods = ref([{
			id: "11",
			name: "小米",
			price: 4999,
			checked: false
		},
		{
			id: "22",
			name: "华为",
			price: 8899,
			checked: false
		},
		{
			id: "33",
			name: "oppo",
			price: 2688,
			checked: false
		},
		{
			id: "44",
			name: "苹果",
			price: 9999,
			checked: false
		},
	])
	// 全选状态
	const allChecked = ref(false);
	// 选中的商品ID数组
	const itemGroup = ref([]);
	// 计算属性：选中的商品数量
	const totalNumber = computed(() => itemGroup.value.length)
	// 计算属性：选中的商品总价，过滤>求和
	const totalPrice = computed(() => {
		return goods.value.filter(item => item.checked).reduce((prev, curr) => prev + curr.price, 0)
	})
	// 单个商品选中状态变化时的处理函数
	function itemChange(e) {
		// 更新选中的商品ID数组
		itemGroup.value = e.detail.value
		// 同步更新goods中每个商品的checked状态，includes(item.id)
		goods.value.forEach(item => {
			item.checked = itemGroup.value.includes(item.id)
		})
	}
	// 全选/取消全选处理函数
	function selectAllChange(e) {
		// 取反当前全选状态
		let newValue = !allChecked.value
		// 更新所有商品的选中状态
		goods.value.forEach(item => {
			item.checked = newValue;
		})
		// 更新选中的商品ID数组
		itemGroup.value = newValue ? goods.value.map(item => item.id) : []
	}
	// 删除商品函数
	function remove(index) {
		// 从数组中移除指定索引的商品
		goods.value.splice(index, 1);
		// 更新选中的商品ID数组
		itemGroup.value = goods.value.filter(item => item.checked).map(item => item.id);
	}
	// 监听goods的变化，自动更新全选状态
	watch(goods, () => {
		allChecked.value = goods.value.every(item => item.checked)
	}, {
		deep: true
	})
</script>
<template>
	<view class="out">
		<checkbox-group @change="itemChange">
			<view class="item" v-for="(item,index) in goods" :key="item.id">
				<checkbox :value="item.id" :checked="item.checked"></checkbox>
				<text class="title">{{item.name}}</text>
				<text class="price">{{item.price}}元</text>
				<text class="del" @click="remove(index)">删除</text>
			</view>
		</checkbox-group>

		<view class="card">
			<checkbox-group @change="selectAllChange">
				<label>
					<checkbox :checked="allChecked" /><text>全选</text>
				</label>
			</checkbox-group>
			<view class="text">
				<view class="number">共{{totalNumber}}件商品</view>
				<view class="total">总计:{{totalPrice}}元</view>
			</view>
		</view>


	</view>
</template>
<style lang="scss" scoped>
	.out {
		padding: 10px;

		.item {
			padding: 10px 0;

			.price {
				margin: 0 20px;
			}

			.del {
				color: #c00;
				margin-left: 30px;
			}
		}

		.card {
			border-top: 1px solid #eee;
			margin-top: 20px;
			padding: 10px 0;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.text {
				display: flex;
				align-items: center;

				.total {
					margin-left: 20px;
				}
			}
		}
	}
	
	
	
	for
	
	
	
	
</style>